<template>
  <div class="main">
    <mine-title>经典算法预测</mine-title>
    <div class="content" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="12">
          <div>
            <el-form
              ref="form"
              :model="form"
              label-width="120px"
              :rules="rules"
            >
              <el-form-item label="文件上传" prop="file">
                <mine-upload
                  ref="upload"
                  :fileType="accept"
                  @change="onChange"
                ></mine-upload>
              </el-form-item>
              <el-form-item label="版本号：" prop="version">
                <el-input
                  type="textarea"
                  v-model="form.version"
                  autosize
                  style="width: 512px"
                ></el-input>
              </el-form-item>
              <el-form-item class="form-btn-row">
                <mine-button type="primary" @click="onCancel" secondary
                  >取 消
                </mine-button>
                <mine-button type="primary" @click="onSubmit"
                  >保 存
                </mine-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import request from "@/modules/index/utils/request";
import dictAdmin from "../../../store/modules/dictAdmin";

export default {
  name: "addDict",
  data() {
    return {
      form: {
        creater: "",
        algoname: "",
        language: "",
        counts: "",
        createTime: "",
        purpose: "",
        remarks: "",
        id: 0,
        number: 0,
        templateId: this.$store.state.codeDetect.currentPreviewLeftRowId,
        version: "",
      },
      rules: {
        fileName: [
          { required: true, message: "请填写算法名称", trigger: "blur" },
        ],
      },
      loading: false,
      fileList: [],
    };
  },
  watch: {
    // "$route.query": {
    //   immediate: true,
    //   handler(val) {
    //     // 如果是编辑页面，先做页面数据的回显
    //     if (val.isEdit) {
    //       this.form = this.$store.state.codeDetect.algoFileListRowData;
    //     }
    //   },
    // },
  },
  computed: {
    accept() {
      if (this.form.fileType === "") {
        return ".txt,.csv,.xls,.xlsx,.zip";
      } else if (
        ["data_predict", "txt_classify", "data_unsupervised"].includes(
          this.form.fileType
        )
      ) {
        return ".txt,.csv,.xls,.xlsx";
      } else if (
        ["img_classify", "voice_classify", "img_detection"].includes(
          this.form.fileType
        )
      ) {
        return ".zip";
      }
      return ".txt,.csv,.xls,.xlsx,.zip";
    },
  },
  methods: {
    onChange(data) {
      this.form.file = data.file;
      this.fileList = [data.file];
    },
    onSubmit() {
      let _this = this;
      this.$refs.form.validate(async (valid, object) => {
        let { form } = _this;
        form.type = 2;
        if (valid) {
          this.loading = true;
          let formData = new FormData();
          formData.append("file", this.form.file.raw);
          if (this.$webview2.isWPF) {
            // 这里对文件的处理需要转成base64的格式后上传
            let reader = new FileReader();
            reader.readAsDataURL(this.form.file.raw);
            reader.onload = async (e) => {
              formData = e.target.result;
              await this.$webview2.sendWebView2(
                `/algoVersionFile/upload?templateId=${this.form.templateId}&version=${this.form.version}&type=2`,
                "post",
                "multipart/form-data",
                {
                  file: formData,
                  fileName: this.form.file.name,
                },
                false
              );
              await window.chrome.webview.addEventListener(
                "message",
                (e) => {
                  let res = e.data.response;
                  // TODO： 定制后台数据处理
                  if (res.status === 200) {
                    _this
                      .$confirm("保存成功，是否需要返回列表？", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                      })
                      .then(() => {
                        _this.onCancel();
                      })
                      .catch(() => {});
                  } else {
                    _this.loading = false;
                    _this.$message.error(res.msg || "新建失败");
                    return;
                  }
                },
                { once: true }
              );
            };
          } else {
            request({
              url: `algoVersionFile/upload?templateId=${this.form.templateId}&version=${this.form.version}&type=2`, //接口
              method: "post",
              data: formData,
              headers: {
                "Content-Type": "multipart/form-data",
              },
            }).then((response) => {
              let result = response.data;
              if (!result.success) {
                this.loading = false;
                this.$message.error(result.msg || "新建失败");
                return;
              }
              this.$confirm("保存成功，是否需要返回列表？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.onCancel();
                })
                .catch(() => {});
            });
            // }
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.form = {
        creater: "",
        algoname: "",
        language: "",
        id: 0,
        purpose: "0",
        // number: 0,
      };
      this.$router.push({
        path: "/code/predictList",
        query: { rowId: this.$store.state.codeDetect.currentPreviewLeftRowId },
      });
    },
  },
  created() {
    // this.form.number = ++this.$store.state.dictAdmin.dictNumber;
    this.$store.commit("SET_BREADCRUMB", [
      { title: "算法文件", path: "/code/predictList" },
      { title: "新增", path: "" },
    ]);
  },
};
</script>

<style scoped>
</style>
